﻿Option Explicit On
Option Strict On

Imports System
Imports System.Xml
Imports System.Configuration
Imports System.Reflection
Imports System.Collections.Specialized


''' <summary>
''' 설정 파일(실행파일명.config)의 정보에 access(읽기/쓰기) 하는 기능을 제공한다.
''' </summary>
''' <remarks></remarks>
Public Class Config

#Region "전역 변수 등 정의"

#End Region
    


#Region "함수(Sub, Function) 정의"



    ''' <summary>
    ''' 공유 인스턴스로 사용하기 위하여 인스턴스 생성을 할 수 없도록 Pravate 접근자로 막음
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Config()

    End Sub



    ''' <summary>
    ''' 설정 파일에서 입력 파라미터 조건에 해당하는 값(value 속성) 값을 반환한다.
    ''' </summary>
    ''' <param name="section">section 이름</param>
    ''' <param name="key">key 이름</param>
    ''' <returns>value 값</returns>
    ''' <remarks></remarks>
    Public Shared Function ReadSetting(ByVal section As String, ByVal key As String) As String

        Dim value As String

        If (section = "appSettings") Then
            value = ConfigurationManager.AppSettings(key)
        Else
            Dim sectionGeneral As NameValueCollection
            sectionGeneral = CType(ConfigurationManager.GetSection(section), NameValueCollection)
            value = sectionGeneral.GetValues(key)(0)
        End If

        Return value

    End Function



    ''' <summary>
    ''' 설정 파일의 설정 정보를 수정 또는 추가한다.
    ''' </summary>
    ''' <param name="section">section</param>
    ''' <param name="key">key</param>
    ''' <param name="value">값</param>
    ''' <remarks></remarks>
    Public Shared Sub WriteSetting(ByVal section As String, ByVal key As String, ByVal value As String)
        Dim doc As XmlDocument
        Dim node As XmlNode

        doc = loadConfigDocument()
        node = doc.SelectSingleNode("//" + section)

        If (node Is Nothing) Then
            Throw New InvalidOperationException(section + " section not found in config file.")
        End If

        Try
            Dim elem As XmlElement
            elem = CType(node.SelectSingleNode(String.Format("//add[@key='{0}']", key)), XmlElement)

            If (Not elem Is Nothing) Then
                elem.SetAttribute("value", value)
            Else
                elem = doc.CreateElement("add")
                elem.SetAttribute("key", key)
                elem.SetAttribute("value", value)
                node.AppendChild(elem)
            End If

            doc.Save(getConfigFilePath())

        Catch ex As Exception
            Throw ex
        End Try
    End Sub



    Public Shared Sub RemoveSetting(ByVal section As String, ByVal key As String)

        Dim doc As XmlDocument
        Dim node As XmlNode

        doc = loadConfigDocument()
        node = doc.SelectSingleNode("//" + section)

        Try
            If (node Is Nothing) Then
                Throw New InvalidOperationException(section + " section not found in config file.")
            Else
                node.RemoveChild(node.SelectSingleNode(String.Format("//add[@key='{0}']", key)))
                doc.Save(getConfigFilePath())
            End If
        Catch ex As NullReferenceException
            Throw New Exception(String.Format("The key {0} does not exist.", key), ex)
        End Try

    End Sub



    Private Shared Function loadConfigDocument() As XmlDocument

        Dim doc As XmlDocument

        Try
            doc = New XmlDocument
            doc.Load(getConfigFilePath)
            Return doc
        Catch e As System.IO.FileNotFoundException
            Throw New Exception("No configuration file found.", e)
        End Try

    End Function



    Private Shared Function getConfigFilePath() As String

        Return Assembly.GetExecutingAssembly().Location + ".config"

    End Function

#End Region

End Class